<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import http from "@/request/http.js";

const goodsList = ref([]) // 商品列表
const orderList = ref([]) // 订单列表
const userPoints = ref(0) // 用户当前积分
const userLevel = ref(1) // 用户当前等级
const total = ref(0) // 商品总数
const orderTotal = ref(0) // 订单总数
const pageSize = ref(8) // 每页条数
const currentPage = ref(1) // 商品当前页
const orderCurrentPage = ref(1) // 订单当前页
const isExchanging = ref(false) // 兑换中状态
const exchangingId = ref(null) // 正在兑换的商品ID
// 初始化加载数据
onMounted(() => {
  fetchUserInfo() // 获取用户积分和等级
  fetchGoodsList() // 获取商品列表
  fetchOrderList() // 获取订单列表
})

// 获取用户信息（积分、等级）
const fetchUserInfo = async () => {
  try {
    const res = await http.get('/points/info')
    if (res.code === 200) {
      userPoints.value = res.data.availablePoints || 0
      userLevel.value = res.data.level || 1
    }
  } catch (err) {
    ElMessage.error('获取用户信息失败')
  }
}

// 获取商品列表
const fetchGoodsList = async () => {
  try {
    const res = await http.get('/points/mall/goods', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        userLevel: userLevel.value
      }
    })
    if (res.code === 200) {
      goodsList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (err) {
    ElMessage.error('获取商品列表失败')
  }
}


// 获取订单列表
const fetchOrderList = async () => {
  try {
    const res = await http.get('/points/mall/orders', {
      params: {
        pageNum: orderCurrentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res.code === 200) {
      orderList.value = res.data.records || []
      orderTotal.value = res.data.total || 0
    }
  } catch (err) {
    ElMessage.error('获取订单列表失败')
  }
}
// 检查是否可兑换（前端校验）
const canExchange = (goods) => {
  if (goods.stock <= 0) return false
  if (userPoints.value < goods.pointsNeeded) return false
  if (userLevel.value < (goods.levelLimit || 1)) return false
  return true
}

// 处理兑换逻辑
const handleExchange = async (goods) => {
  try {
    await ElMessageBox.confirm(
        `确认兑换【${goods.goodsName}】吗？将消耗${goods.pointsNeeded}积分`,
        '兑换确认',
        {
          confirmButtonText: '确认兑换',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
  } catch (err) {
    return ElMessage.info('已取消兑换')
  }

  isExchanging.value = true
  exchangingId.value = goods.goodsId
  try {
    const res = await http.post('/points/mall/exchange', {
      goodsId: goods.goodsId
    })
    if (res.code === 200) {
      ElMessage.success('兑换成功！')
      fetchUserInfo()
      fetchGoodsList()
      fetchOrderList()
    } else {
      ElMessage.error(res.msg || '兑换失败')
    }
  } catch (err) {
    ElMessage.error('兑换请求失败，请重试')
  } finally {
    isExchanging.value = false
    exchangingId.value = null
  }
}


// 格式化时间
const formatTime = (row) => {
  return row.orderTime ? new Date(row.orderTime).toLocaleString() : '-'
}

// 格式化订单状态
const formatStatus = (row) => {
  const statusMap = {
    0: '待发货',
    1: '已发货',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[row.status] || '未知状态'
}

// 商品分页切换
const handlePageChange = (page) => {
  currentPage.value = page
  fetchGoodsList()
}

// 订单分页切换
const handleOrderPageChange = (page) => {
  orderCurrentPage.value = page
  fetchOrderList()
}
</script>

<template>
  <div class="points-mall">
    <!-- 页面标题与用户积分信息 -->
    <div class="header">
      <h2>积分商城</h2>
      <div class="user-points">
        <span>当前积分：</span>
        <span class="points-num">{{ userPoints }}</span>
        <span class="level-tag">Lv.{{ userLevel }}</span>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-card class="goods-card" shadow="hover">
      <div class="goods-list">
        <el-row :gutter="20">
          <el-col v-for="goods in goodsList" :key="goods.goodsId" :span="6">
            <el-card class="goods-item">
              <div class="goods-info">
                <h3 class="goods-name">{{ goods.goodsName }}</h3>
                <div class="goods-meta">
                  <span class="points-needed">所需积分：{{ goods.pointsNeeded }}</span>
                  <span class="level-limit">等级要求：Lv.{{ goods.levelLimit || 1 }}</span>
                </div>
                <div :class="{ low: goods.stock <= 10 }" class="stock">
                  库存：{{ goods.stock }}件
                  <span v-if="goods.stock <= 10">(库存紧张)</span>
                </div>

                <!-- 兑换按钮 -->
                <el-button
                    v-loading="isExchanging && exchangingId === goods.goodsId"
                    :disabled="!canExchange(goods) || isExchanging"
                    class="exchange-btn"
                    loading-size="small"
                    type="primary"
                    @click="handleExchange(goods)"
                >
                  立即兑换
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 商品分页 -->
      <el-pagination
          v-if="total > 0"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          class="pagination"
          layout="prev, pager, next, total"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 兑换订单列表 -->
    <el-card class="orders-card" shadow="hover" style="margin-top: 20px">
      <h3 slot="header">我的兑换记录</h3>
      <el-table :data="orderList" border>
        <el-table-column label="订单ID" prop="orderId" width="180"/>
        <el-table-column label="商品名称" prop="goodsName" width="180">
        </el-table-column>
        <el-table-column label="消耗积分" prop="pointsUsed" width="120"/>
        <el-table-column
            :formatter="formatTime"
            label="兑换时间"
            prop="orderTime"
            width="200"
        />
        <el-table-column
            :formatter="formatStatus"
            label="状态"
            prop="orderStatus"
            width="120"
        />
      </el-table>

      <!-- 订单分页 -->
      <el-pagination
          v-if="orderTotal > 0"
          :current-page="orderCurrentPage"
          :page-size="pageSize"
          :total="orderTotal"
          class="pagination"
          layout="prev, pager, next, total"
          @current-change="handleOrderPageChange"
      />
    </el-card>
  </div>
</template>


<style scoped>
.points-mall {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.user-points {
  display: flex;
  align-items: center;
  gap: 10px;
}

.points-num {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.level-tag {
  background: #409eff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.goods-list {
  margin-bottom: 20px;
}

.goods-item {
  height: 100%;
  overflow: hidden;
  transition: all 0.3s;
}

.goods-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.goods-info {
  padding: 15px;
  text-align: center;
}

.goods-name {
  font-size: 16px;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.points-needed {
  color: #f56c6c;
}

.level-limit {
  color: #67c23a;
}

.stock {
  font-size: 13px;
  color: #666;
  margin-bottom: 15px;
}

.stock.low {
  color: #e6a23c;
}

.exchange-btn {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.orders-card {
  margin-top: 30px;
}
</style>